<template>
  <div class="lov-config-page">
    <div class="page-header">
      <h2>LOV 配置管理</h2>
      <a-button type="primary" @click="handleAdd">
        <template #icon><PlusOutlined /></template>
        新建配置
      </a-button>
    </div>

    <!-- 配置列表 -->
    <a-table 
      :dataSource="configList" 
      :columns="tableColumns"
      :loading="loading"
      :rowKey="(record: LovConfig) => record.id!"
      bordered
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'enabled'">
          <a-tag :color="record.enabled ? 'success' : 'error'">
            {{ record.enabled ? '启用' : '禁用' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
          <a-button type="link" danger size="small" @click="handleDelete(record)">删除</a-button>
        </template>
      </template>
    </a-table>

    <!-- 配置对话框 -->
    <a-modal
      v-model:open="dialogVisible"
      :title="dialogTitle"
      width="900px"
      :maskClosable="false"
      @ok="handleSave"
      :confirmLoading="saving"
    >
      <a-form :model="form" :label-col="{ style: { width: '120px' } }" ref="formRef" :rules="rules">
        <a-tabs v-model:activeKey="activeTab">
          <a-tab-pane key="basic" tab="基本信息">
            <a-row :gutter="20">
              <a-col :span="12">
                <a-form-item label="代码" name="lovCode">
                  <a-input v-model:value="form.lovCode" placeholder="LOV_STUDENT_DYNAMIC" :disabled="isEdit" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="名称" name="lovName">
                  <a-input v-model:value="form.lovName" placeholder="学生查询(动态SQL)" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-form-item label="描述" name="lovDesc">
              <a-input v-model:value="form.lovDesc" placeholder="支持年龄范围和姓名关键词的动态查询" />
            </a-form-item>

            <a-row :gutter="20">
              <a-col :span="12">
                <a-form-item label="弹窗标题" name="title">
                  <a-input v-model:value="form.title" placeholder="LOV" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="数据源类型" name="dataSourceType">
                  <a-select v-model:value="form.dataSourceType">
                    <a-select-option value="SQL">自定义SQL</a-select-option>
                    <a-select-option value="URL">URL请求</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>

            <a-form-item label="自定义SQL" name="dataSourceSql" v-if="form.dataSourceType === 'SQL'">
              <a-textarea
                v-model:value="form.dataSourceSql"
                placeholder="SELECT stu_id, stu_name, stu_age FROM student&#10;<where>&#10;  <if test=&quot;minAge != null&quot;>&#10;    AND stu_age >= #{minAge}&#10;  </if>&#10;</where>"
                :rows="6"
              />
              <div style="margin-top: 5px; font-size: 12px; color: #8c8c8c;">
                💡 提示：无需手动添加&lt;script&gt;标签，后端会自动处理。支持MyBatis动态SQL（&lt;if&gt;、&lt;where&gt;等标签）
              </div>
            </a-form-item>

            <a-form-item label="数据源URL" name="dataSourceUrl" v-if="form.dataSourceType === 'URL'">
              <a-input v-model:value="form.dataSourceUrl" placeholder="http://api.example.com/data" />
            </a-form-item>

            <a-row :gutter="20">
              <a-col :span="12">
                <a-form-item label="值字段" name="valueField">
                  <a-input v-model:value="form.valueField" placeholder="stu_id" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="显示字段" name="displayField">
                  <a-input v-model:value="form.displayField" placeholder="stu_name" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="20">
              <a-col :span="8">
                <a-form-item label="页大小" name="pageSize">
                  <a-input-number v-model:value="form.pageSize" :min="5" :max="100" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="弹窗高度" name="dialogHeight">
                  <a-input-number v-model:value="form.dialogHeight" :min="200" :max="800" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="弹窗宽度" name="dialogWidth">
                  <a-input-number v-model:value="form.dialogWidth" :min="400" :max="1200" style="width: 100%" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="20">
              <a-col :span="12">
                <a-form-item label="是否启用">
                  <a-switch v-model:checked="form.enabled" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>

          <a-tab-pane key="columns" tab="列配置">
            <div class="column-config-header">
              <a-button type="primary" size="small" @click="handleAddColumn">
                <template #icon><PlusOutlined /></template>
                添加列
              </a-button>
            </div>
            <a-table 
              :dataSource="form.columns" 
              :columns="columnTableColumns"
              :pagination="false"
              :rowKey="(record: LovColumnConfig, index: number) => index"
              bordered
              size="small"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'displayName'">
                  <a-input v-model:value="record.displayName" size="small" />
                </template>
                <template v-else-if="column.key === 'fieldName'">
                  <a-input v-model:value="record.fieldName" size="small" />
                </template>
                <template v-else-if="column.key === 'columnWidth'">
                  <a-input-number v-model:value="record.columnWidth" size="small" :min="50" style="width: 100%" />
                </template>
                <template v-else-if="column.key === 'visible'">
                  <a-switch v-model:checked="record.visible" size="small" />
                </template>
                <template v-else-if="column.key === 'queryable'">
                  <a-switch v-model:checked="record.queryable" size="small" />
                </template>
                <template v-else-if="column.key === 'columnOrder'">
                  <a-input-number v-model:value="record.columnOrder" size="small" :min="0" style="width: 100%" />
                </template>
                <template v-else-if="column.key === 'queryOrder'">
                  <a-input-number v-model:value="record.queryOrder" size="small" :min="0" style="width: 100%" />
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button type="link" danger size="small" @click="handleDeleteColumn(index)">删除</a-button>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import request from '@/utils/request'

interface LovColumnConfig {
  displayName: string
  fieldName: string
  columnWidth: number
  visible: boolean
  queryable: boolean
  columnOrder: number
  queryOrder: number
}

interface LovConfig {
  id?: number
  lovCode: string
  lovName: string
  lovDesc: string
  title: string
  dataSourceSql: string
  dataSourceType: string
  dataSourceUrl: string
  displayField: string
  valueField: string
  pageSize: number
  dialogHeight: number
  dialogWidth: number
  enabled: boolean
  columns: LovColumnConfig[]
}

const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新建LOV配置')
const isEdit = ref(false)
const activeTab = ref('basic')
const formRef = ref()
const configList = ref<LovConfig[]>([])

const form = reactive<LovConfig>({
  lovCode: '',
  lovName: '',
  lovDesc: '',
  title: 'LOV',
  dataSourceSql: '',
  dataSourceType: 'SQL',
  dataSourceUrl: '',
  displayField: '',
  valueField: '',
  pageSize: 10,
  dialogHeight: 400,
  dialogWidth: 700,
  enabled: true,
  columns: []
})

const rules = {
  lovCode: [{ required: true, message: '请输入LOV代码', trigger: 'blur' }],
  lovName: [{ required: true, message: '请输入LOV名称', trigger: 'blur' }],
  dataSourceSql: [{ required: true, message: '请输入SQL语句', trigger: 'blur' }],
  valueField: [{ required: true, message: '请输入值字段', trigger: 'blur' }],
  displayField: [{ required: true, message: '请输入显示字段', trigger: 'blur' }],
}

const tableColumns = [
  { title: '代码', dataIndex: 'lovCode', key: 'lovCode', width: 200 },
  { title: '名称', dataIndex: 'lovName', key: 'lovName', width: 150 },
  { title: '描述', dataIndex: 'lovDesc', key: 'lovDesc' },
  { title: '类型', dataIndex: 'dataSourceType', key: 'dataSourceType', width: 80 },
  { title: '状态', key: 'enabled', width: 80 },
  { title: '操作', key: 'action', width: 180, fixed: 'right' },
]

const columnTableColumns = [
  { title: '显示名称', key: 'displayName', width: 120 },
  { title: '字段名', key: 'fieldName', width: 120 },
  { title: '列宽', key: 'columnWidth', width: 100 },
  { title: '表格可见', key: 'visible', width: 90 },
  { title: '可查询', key: 'queryable', width: 90 },
  { title: '列序号', key: 'columnOrder', width: 100 },
  { title: '查询顺序', key: 'queryOrder', width: 100 },
  { title: '操作', key: 'action', width: 80, fixed: 'right' },
]

// 加载配置列表
async function loadConfigList() {
  loading.value = true
  try {
    const response = await request.get('/lov/configs')
    configList.value = response.data || []
  } catch (error) {
    console.error('加载配置列表失败:', error)
    message.error('加载配置列表失败')
  } finally {
    loading.value = false
  }
}

// 新建
function handleAdd() {
  isEdit.value = false
  dialogTitle.value = '新建LOV配置'
  resetForm()
  dialogVisible.value = true
}

// 编辑
function handleEdit(row: LovConfig) {
  isEdit.value = true
  dialogTitle.value = '编辑LOV配置'
  Object.assign(form, row)
  if (!form.columns) {
    form.columns = []
  }
  dialogVisible.value = true
  activeTab.value = 'basic'
}

// 删除
function handleDelete(row: LovConfig) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除该配置吗？',
    onOk: async () => {
      try {
        await request.delete(`/lov/config/${row.id}`)
        message.success('删除成功')
        loadConfigList()
      } catch (error) {
        console.error('删除失败:', error)
        message.error('删除失败')
      }
    },
  })
}

// 保存
async function handleSave() {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true
    
    if (isEdit.value) {
      await request.put('/lov/config', form)
      message.success('更新成功')
    } else {
      await request.post('/lov/config', form)
      message.success('创建成功')
    }
    dialogVisible.value = false
    loadConfigList()
  } catch (error) {
    console.error('保存失败:', error)
    if (error && typeof error === 'object' && 'errorFields' in error) {
      // 表单验证错误
      return
    }
    message.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 添加列
function handleAddColumn() {
  form.columns.push({
    displayName: '',
    fieldName: '',
    columnWidth: 150,
    visible: true,
    queryable: false,
    columnOrder: form.columns.length,
    queryOrder: form.columns.length
  })
}

// 删除列
function handleDeleteColumn(index: number) {
  form.columns.splice(index, 1)
}

// 重置表单
function resetForm() {
  form.lovCode = ''
  form.lovName = ''
  form.lovDesc = ''
  form.title = 'LOV'
  form.dataSourceSql = ''
  form.dataSourceType = 'SQL'
  form.dataSourceUrl = ''
  form.displayField = ''
  form.valueField = ''
  form.pageSize = 10
  form.dialogHeight = 400
  form.dialogWidth = 700
  form.enabled = true
  form.columns = []
  activeTab.value = 'basic'
}

onMounted(() => {
  loadConfigList()
})
</script>

<style scoped>
.lov-config-page {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-header h2 {
  margin: 0;
}
.column-config-header {
  margin-bottom: 10px;
}
</style>

